package com.example.mapsapp;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.example.mapsapp.Friends.GetFriendsTask;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class Favorites extends Activity {

	public static ArrayAdapter<String> ad ;
	public static ListView favList;
	public static ArrayList<String> list;
	public static String fav;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_favorites);
		try{
			new GetFavoritesTask().execute();
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_favorites, menu);
		return true;
	}
	

	public class GetFavoritesTask extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... params) {
			// TODO: attempt authentication against a network service.
			String response = "";
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			
			if(networkInfo != null && networkInfo.isConnected())
			{
				ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
				n.add(new BasicNameValuePair("user", Login.user));
				
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost("http://softeng.cs.uwosh.edu/students/cs342g2/getFavorites.php");
				try
				{
					httppost.setEntity(new UrlEncodedFormEntity(n));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					response = httpClient.execute(httppost, respondHandler);
				}
				catch(Exception e){
					
				}
			}
			return response;
		}
		
		@Override
		protected void onPostExecute(String resp){
			
			//System.out.println("XML RESP:");
			//System.out.println(resp);

			 
			try {
				//System.out.println("RESP:" + resp);
				DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
				DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
				Document doc = dBuilder.parse(new ByteArrayInputStream(resp.getBytes()));
				
				 
				doc.getDocumentElement().normalize();
			 
				System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
			 
				NodeList nList = doc.getElementsByTagName("location");
				 list = new ArrayList<String>();
				//ArrayList<String> list = new ArrayList<String>();
				//System.out.println("----------------------------");
				for (int i = 0; i < nList.getLength(); i++) {
					
					Node nNode = nList.item(i);
			 
					//System.out.println("Current Element :" + nNode.getNodeName());
					if (nNode.getNodeType() == Node.ELEMENT_NODE) {
			 
						Element ele = (Element) nNode;
						
						String fav = ele.getTextContent();
					
						list.add(fav);
						
						//System.out.println("MESSAGE: " + eElement.getTextContent());
			 
					}
				}
				
				favList = (ListView) findViewById(R.id.listFavorites);
				for(String g:list)
				{
			        System.out.println("i have values  :" + g);
				}
			    ad = new ArrayAdapter<String>(Favorites.this, android.R.layout.simple_list_item_1, list);
				favList.setAdapter(ad);
				favList.setOnItemClickListener(new OnItemClickListener() {
		            public void onItemClick(AdapterView<?> arg0, View view, int position, long index) {
		             	//Do something on click
		        						ListView list = (ListView) findViewById(R.id.listFavorites);
		        						
		        						fav = list.getItemAtPosition(position).toString();
		        						

		        							   AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Favorites.this);
		        						 
		        									// set title
		        									alertDialogBuilder.setTitle("View Locaton?");
		        						 
		        									// set dialog message
		        									alertDialogBuilder
		        										.setMessage("View " + fav + "?")
		        										.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
		        											public void onClick(DialogInterface dialog,int id) {
		        												// if this button is clicked, close
		        												// current activity
		        												


		        												Intent i = new Intent(Favorites.this, Find_Favorite.class);
		        												i.putExtra("location", fav);
		        												startActivity(i);
		        												
		        												
		        												dialog.cancel();
		        											}
		        										  })
		        										  .setNegativeButton("No",new DialogInterface.OnClickListener() {
		        												public void onClick(DialogInterface dialog,int id) {
		        													
		        													
		        													dialog.cancel();
		        												}
		        											  });
		        									//EditText input = (EditText) findViewById(R.id.frienddialogtext);
		        										// create alert dialog
		        										AlertDialog alertDialog = alertDialogBuilder.create();
		        						 
		        										// show it
		        										alertDialog.show();
		        									
		        							
		            }
		        });
				
			} catch (Exception e) {
				e.printStackTrace();
		    }
		}
	}
}
